package com.updesignsz.api.util;

import com.updesignsz.commom.util.StringUtil;
import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;

public class ResponseUtil {

    private ResponseUtil() {
    }

    public static void outJson(String jsonString, HttpServletResponse response) {
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.setHeader("Cache-Control", "no-cache");
            PrintWriter out = response.getWriter();
//            System.out.println(jsonString);
            out.print(jsonString);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 接收request流转成JSON对象
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static JSONObject getRequestAsJSONObject(HttpServletRequest request) throws IOException {
        String ret = request.getAttribute("data").toString();
        return StringUtil.isNotEmpty(ret) ? JSONObject.fromObject(ret) : new JSONObject();
    }


    /**
     * 接收request流转成字符串
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static String getRequestStr(HttpServletRequest request) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int read;
        InputStream in = request.getInputStream();
        do {
            read = in.read(buf);
            if (read > 0)
                out.write(buf, 0, read);
        } while (read > 0);
        String ret = out.toString("utf-8");
        out.close();
        out = null;
        return ret;
    }

    public static String doGet(String url,String param)
    {
        StringBuilder result = new StringBuilder();
        try{
            String urlName = url + "?"+param;//
            URL U = new URL(urlName);
            URLConnection connection = U.openConnection();
            connection.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine())!= null)
            {
                result.append(line);
            }
            in.close();
        }catch(Exception e){
           e.printStackTrace();
        }
        return result.toString();
    }

    public static void main(String[] args) {
        String url="http://api.yunrunyuqing.com/api/place";
        String param="parentId=018";

        System.out.println(doGet(url,param));
    }

}
